//
//  StudentAddActivityViewController.m
//  ECBBusinessCamp
//
//  Created by rimi on 16/6/23.
//  Copyright © 2016年 邓毕华. All rights reserved.
//

#import "StudentAddActivityViewController.h"

@interface StudentAddActivityViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

#pragma mark -- 属性 --
#pragma mark --
@property (weak, nonatomic) IBOutlet UITextField *titleName;
@property (weak, nonatomic) IBOutlet UILabel *actor;

@property (weak, nonatomic) IBOutlet UITextField *personLine;
@property (weak, nonatomic) IBOutlet UITextField *activityPlace;
@property (weak, nonatomic) IBOutlet UITextField *forecast;//简介

//btn
//活动时间段//报名截止时间
@property (weak, nonatomic) IBOutlet UIButton *statrTime;
@property (nonatomic,strong) NSDate *startTimeDate;

@property (weak, nonatomic) IBOutlet UIButton *endTime;
@property (nonatomic,strong) NSDate *endTimeDate;

@property (weak, nonatomic) IBOutlet UIButton *timeLine;
@property (nonatomic,strong) NSDate *timeLineDate;

@property (weak, nonatomic) IBOutlet UIButton *addImage;
@property (nonatomic,strong) UIImage *btnImage;
@property (nonatomic,strong) NSMutableDictionary *fileDic;

@property (weak, nonatomic) IBOutlet UIButton *releaseBtn;//发布
@property (weak, nonatomic) IBOutlet UIButton *cancel;//取消

@property (nonatomic,strong) NSMutableDictionary *param;

@property (nonatomic, strong) UIImagePickerController *imagePickerController; /**< 相册拾取器 */
@property (nonatomic, strong) UIAlertController *alertController;//表单
@property (nonatomic, strong) UIDatePicker *datePick;//滚轮

@end

@implementation StudentAddActivityViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.5];
    //初始化相册选择器
    _imagePickerController = [[UIImagePickerController alloc] init];

    //数据的显示
    _actor.text = [LoginUserInfo defaultUserInfo].username;
    
}

//数据
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //添加键盘监听
    [self addKeyNotification];
    
}

#pragma mark -- 数据请求前处理 --
#pragma mark --
- (void)dataSources{
    //数据处理~文本/data/picture
    //取图片
    
    int totalNum = [_personLine.text intValue];
    if (_titleName.text.length == 0 || _forecast.text.length == 0 || _activityPlace.text == 0 ||_startTimeDate == nil || _endTimeDate == nil ||_timeLineDate == nil) {
        [MBProgressHUD showError:@"请输入完整的活动"];
        return;
    }
    
    _param = [NSMutableDictionary dictionaryWithObjects:@[_titleName.text,_forecast.text,_actor.text,_activityPlace.text,_startTimeDate,_endTimeDate,@(totalNum),_timeLineDate] forKeys:@[@"title",@"desce",@"userName",@"place",@"startTime",@"lastTime",@"totalNum",@"catoffday"]];
    
    UIImage *image = _btnImage;
    //返回jpg类型 的data
    NSData *data = UIImageJPEGRepresentation(image, 0.9);
    _fileDic = [NSMutableDictionary dictionary];
    _fileDic[@"data"] = data;
    _fileDic[@"nameKey"] = @"pic";
    _fileDic[@"fileName"] = @"imageOfHeader.jpg";
    _fileDic[@"fileType"] = @"image/jpeg";
   
    [self dataLoad];//网络请求
   
}

#pragma mark -- 网络请求 --
#pragma mark --
//网络请求
- (void)dataLoad{
    
    [[TQNetworkTool sharedNetWorkingTool]requestURL:BASEURLAPPEND(STUDENTADDACTIVITY_URL) withParams:_param fileData:_fileDic finished:^(NSDictionary *responseObject, NSError *error) {
        
        NSLog(@"responseObject----%@",responseObject);
        
        if ([responseObject[@"status"] integerValue]== 1) {
            [MBProgressHUD showSuccess:@"发布成功"];
            
            [self.onlyview removeFromSuperview];
            [self.view removeFromSuperview];
            [self removeFromParentViewController];
        }else{
            [MBProgressHUD showError:@"发布失败"];
            NSLog(@"error%@",error);
        }
        
    }];
    
}


#pragma mark -- 监听 --
#pragma mark --
// 添加键盘监听
- (void)addKeyNotification {
    NSNotificationCenter * notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(keyboardFrameAppear) name:UIKeyboardDidShowNotification object:nil];
    [notificationCenter addObserver:self selector:@selector(keyboardFrameHidden) name:UIKeyboardDidHideNotification object:nil];
    
}
// 键盘将要显示
- (void)keyboardFrameAppear{
    
    CGFloat f = 160;
    if ( _activityPlace.isEditing ||  _forecast.isEditing) {
       self.view.center = CGPointMake(SCREEN_WIDTH/2,SCREEN_HEIGHT/2 - f );
        [self.view reloadInputViews];

        NSLog(@"显示键盘时_onlyview~%f--%f",_onlyview.center.x,_onlyview.center.y);
    }

}
// 键盘将要隐藏
- (void)keyboardFrameHidden{
    
    if ( _activityPlace.isEnabled ||  _forecast.isEnabled) {
        self.view.center = CGPointMake(SCREEN_WIDTH/2,SCREEN_HEIGHT/2);
        [self.view reloadInputViews];

        NSLog(@"隐藏键盘时%f--%f",_onlyview.center.x,_onlyview.center.y);
    }
}

//移动_onlyview
- (void)move:(BOOL)i{
    
    if (i){//datepicker显示
        self.onlyview.center = CGPointMake(_onlyview.center.x,200);
    }else{
        self.onlyview.center = CGPointMake(_onlyview.center.x, self.onlyview.center.y);
    }
}

- (void)animationOfend{
    [UIView animateWithDuration:0.9 animations:^{
        
        _onlyview.hidden = NO;
        //动画路径
        CABasicAnimation * position = [CABasicAnimation animationWithKeyPath:@"position"];//@"position"里面是图层的属性
        //持续时间
        position.duration = 1.0f;
        //起始帧、起点~id类型~要用NSValue封装
        position.fromValue =[NSValue valueWithCGPoint:_onlyview.center];
        //结束帧
        position.toValue = [NSValue valueWithCGPoint:CGPointMake(1250, 80)];
        //设置重复的次数
        position.repeatCount = 1;
        //设置是否反向执行
        position.autoreverses = NO;
        //设置线性规律
        position.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];    
        //设置动画执行完后，将动画保留在当前值。见上文本
        position.removedOnCompletion = NO;
        position.fillMode = kCAFillModeForwards;//这里是设置动画执行完后，将动画保留在当前值。
        
        [_onlyview.layer addAnimation:position forKey:@"position"];//key是在移除动画时要用的值。
      
        
        _onlyview.transform = CGAffineTransformScale(_onlyview.transform, 0.1, 0.1);

        NSLog(@"缩小");
    } completion:^(BOOL finished) {
        [self.view removeFromSuperview];
        [self removeFromParentViewController];
    }];
}
#pragma mark -- btn --
#pragma mark --

- (IBAction)startTime:(UIButton *)sender {
    
    [self.view addSubview:self.datePick];
    [self move:1];
    NSLog(@"start时间拾取");
    [self dateString:1];
}
- (IBAction)endTime:(UIButton *)sender {
    [self.view addSubview:self.datePick];
    [self move:1];
    NSLog(@"end时间拾取");
    [self dateString:2];
}
- (IBAction)timeLine:(UIButton *)sender {
    [self.view addSubview:self.datePick];
    [self move:1];
    NSLog(@"end时间拾取");
    [self dateString:3];
}
- (IBAction)addImage:(UIButton *)sender {
     NSLog(@"添加图片btn");
    
    _alertController = self.alertController;//getter表单
    //表单位置
    UIPopoverPresentationController *popOver = [_alertController popoverPresentationController];
    popOver.sourceView = _addImage; //下拉式对话框 弹出的位置
    popOver.sourceRect = CGRectMake(0, 0, _addImage.bounds.size.width , _addImage.bounds.size.height);
    
    [self presentViewController:_alertController animated:YES completion:nil];
  
}
- (IBAction)releaseBtn:(UIButton *)sender {
    NSLog(@"发布");
    [self dataSources];//数据准备
    
    
}
- (IBAction)cancel:(UIButton *)sender {
    NSLog(@"取消发布");
    
    [self animationOfend];
    
}


#pragma mark -- <UIImagePickerControllerDelegate> & <UINavigationControllerDelegate> --
#pragma mark --
// 用户选择了某个媒体
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary <NSString *,id> *)info {
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            if ([info[UIImagePickerControllerMediaType] isEqualToString:@"public.image"]) {
                //UIImagePickerControllerMediaType：用户选择的媒体类型，得到的是一个NSString得值，返回@"public.image"或者@"public.movie"，通过这个值我们就可以判断用户选取的是图片还是视频了。
                //UIImagePickerControllerOriginalImage：没有被编辑过的原始图像。
                //UIImagePickerControllerEditedImage：用户编辑过后的图像（allowsEditing属性设为YES，通过编辑的到的图像）。
                //UIImagePickerControllerCropRect：返回用户选择的图像区域，它作为一个NSRect数据类型返回。
                //UIImagePickerControllerReferenceURL：返回一个媒体类型的NSURL。
                UIImage *originalImage = info[UIImagePickerControllerOriginalImage];
                
                [_addImage setBackgroundImage:originalImage forState:UIControlStateNormal];
                _btnImage = originalImage;
                
            }
        }else {
                [_addImage setBackgroundImage:info[UIImagePickerControllerEditedImage] forState:UIControlStateNormal];
            _btnImage = info[UIImagePickerControllerEditedImage];
        }
       [self dismissViewControllerAnimated:YES completion:nil];

}
// 用户点击了取消按钮
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    // 消失相册
    [self.presentedViewController dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark -- touch --
#pragma mark --
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
    [self.datePick removeFromSuperview];
    [self move:0];
    
}
#pragma mark -- 时间数据 --
#pragma mark --
- (void)dateString:(int)t{
    [self.view endEditing:YES];
    
    NSDate *pickerdate = self.datePick.date;
    NSDateFormatter *pickerFormatter = [[NSDateFormatter alloc]init];
    [pickerFormatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];
    NSString *dateString = [pickerFormatter stringFromDate:pickerdate];
    NSLog(@"btn——%d",t);
    switch (t) {
        case 1:
           [self.statrTime setTitle:dateString forState:UIControlStateNormal];
            _startTimeDate = pickerdate;
            break;
        case 2:
            [self.endTime setTitle:dateString forState:UIControlStateNormal];
            _endTimeDate = pickerdate;
            break;
        case 3:
            [self.timeLine setTitle:dateString forState:UIControlStateNormal];
            _timeLineDate = pickerdate;
            break;
        default:
            break;
    }
   
}
#pragma mark -- getter --
#pragma mark --

- (UIAlertController *)alertController{
    
    if (!_alertController) {
        _alertController = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请选择图片来源" preferredStyle:UIAlertControllerStyleActionSheet];
        
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSArray * mediatypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeSavedPhotosAlbum];
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
                _imagePickerController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
                _imagePickerController.mediaTypes = @[mediatypes[0]];
                _imagePickerController.delegate = self;
                _imagePickerController.allowsEditing = YES;
                [self presentViewController:_imagePickerController animated:YES completion:nil];
            }
        }];
        
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"照相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //获取支持的媒体格式
            NSArray * mediatypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
            // 判断是否支持需要设置的sourceType
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                // 1、设置图片拾取器上的sourceType
                _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
                // 2、设置支持的媒体格式
                _imagePickerController.mediaTypes = @[mediatypes[0]];
                // 3、是否进入编辑状态
                _imagePickerController.allowsEditing = YES;
                // 4、设置代理
                _imagePickerController.delegate = self;
                [self presentViewController:_imagePickerController animated:YES completion:nil];
            } else {
                UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"系统模拟器暂不能提供照相功能" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
                [self presentViewController:alert animated:YES completion:nil];
            } }];
            
      
        UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            NSLog(@"取消头像");
        }];

        
        [_alertController addAction:action1];
        [_alertController addAction:action2];
        [_alertController addAction:action3];
        
    }
    return _alertController;
}


- (UIDatePicker *)datePick{
    if (!_datePick) {
        _datePick = [[UIDatePicker alloc]init];
        _datePick.backgroundColor = [UIColor whiteColor];
        _datePick.datePickerMode = UIDatePickerModeDateAndTime;
        
        _datePick.bounds = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT/4);
        NSLog(@"%f",SCREEN_HEIGHT/4);
        _datePick.center = CGPointMake(self.view.center.x, SCREEN_HEIGHT-200);
        
    }
    return _datePick;
    
}

 
@end
